package com.qingzhou.web.controller.common;

import cn.hutool.core.lang.Assert;
import com.qingzhou.common.utils.FileUtil;
import com.qingzhou.common.web.domain.FileVo;
import com.qingzhou.framework.config.FileConfig;
import com.qingzhou.web.service.impl.params.request.PatientDownloadSingleFileForm;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Post;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.DownloadedFile;
import org.noear.solon.core.handle.Result;
import org.noear.solon.core.handle.UploadedFile;

import java.io.File;

/**
 * 文件 操作处理
 * @author xm
 */
@Controller
@Mapping("file")
public class FileController {

    @Inject
    FileConfig fileConfig;

    /**
     * 单文件上传
     */
    @Post
    @Mapping("/upload/file")
    public Result<String> file(UploadedFile file) {
        return Result.succeed(FileUtil.upload(file, fileConfig.getMaxSize(), fileConfig.getFileType(), fileConfig.getSavePath(), fileConfig.getRequestPrefix()));
    }

    /**
     * 单文件上传
     */
    @Post
    @Mapping("/upload/single")
    public Result<FileVo> uploadSingle(UploadedFile file) {
        FileVo filevo = FileUtil.trans(file, fileConfig.getMaxSize(), fileConfig.getFileType(), fileConfig.getSavePath());
        return Result.succeed(filevo);
    }

    @SneakyThrows
    @ApiOperation("下载文件(单文件)")
    @Mapping("/download/single")
    public void downloadSingle(FileVo file, Context ctx) {
        File fileVo = FileUtil.file(fileConfig.getSavePath() + file.getPath());
        Assert.isTrue(FileUtil.exist(fileVo), "文件找不到啦，下载失败");
        ctx.outputAsFile(new DownloadedFile(fileVo,file.getName()));
    }

}
